package com.gs.synedocket.util;

import android.text.TextUtils;

import com.gs.synedocket.apiresult.ApiResultData;
import com.gs.synedocket.callback.IOnSyncListener;
import com.gs.synedocket.constant.AllConstants;
import com.gs.synedocket.constant.HandleCode;
import com.gs.synedocket.constant.SyncStatus;
import com.gs.synedocket.db.bean.SyncBean;
import com.gs.synedocket.db.dao.LogUtil;
import com.gs.synedocket.db.entity.Docket;
import com.gs.synedocket.db.sqlite.DBApi;
import com.gs.synedocket.presenter.SyncDownloadPresenter;
import com.gs.synedocket.view.ISyncDownload;

import java.util.List;

public class SyncDownloadUtil implements ISyncDownload {
    private static volatile SyncDownloadUtil instance;
    private final String[] syncDocket = new String[]{"onHand", "deliveryLogList", "onHandList"};
//    private boolean isDownload;
    private int syncPosition;

    private final SyncDownloadPresenter mPresenter;

    public static SyncDownloadUtil getInstance() {
        if (instance == null) {
            synchronized (SyncDownloadUtil.class) {
                if (instance == null) {
                    instance = new SyncDownloadUtil();
                }
            }
        }
        return instance;
    }

    public SyncDownloadUtil() {
        mPresenter = new SyncDownloadPresenter();
        mPresenter.attachView(this);
    }

    private String getSyncDocket() {
        return syncDocket[syncPosition];
    }

//    public boolean isDownload() {
//        return isDownload;
//    }
//
//    public void setDownload(boolean download) {
//        isDownload = download;
//    }

    public void download() {
        sendDownloading();
        syncDocketOnHand();
    }

    public void downloadOnHandList() {
        sendDownloading();
        syncDocketOnHandList();
    }

    public void downloadLogList() {
        sendDownloading();
        syncDocketLog();
    }

    private void syncDocketOnHand() {
        syncPosition = 0;
        String truckNo = SPUtil.getInstance().getString(AllConstants.TRUCK_NAME);
        String query = DBApi.getInstance().getQueryCacheMap(AllConstants.ON_HAND);
        // 请求时要加上其他两个obj里面的ids
//        StringBuilder otherIds = new StringBuilder();
//        otherIds.append(getQueryCacheIds(AllConstants.LOG_LIST))
//                .append(getQueryCacheIds(AllConstants.ON_HAND_LIST));
        if (TextUtils.isEmpty(query)) {
            syncDocket(null, truckNo, AllConstants.ON_HAND, "");
        } else {
            syncDocket(AllConstants.ON_HAND, query, "");
        }
    }

    private void syncDocketLog() {
        syncPosition = 1;
        String truckNo = SPUtil.getInstance().getString(AllConstants.TRUCK_NAME);
        String query = DBApi.getInstance().getQueryCacheMap(AllConstants.LOG_LIST);
        // 请求时要加上其他两个obj里面的ids
//        StringBuilder otherIds = new StringBuilder();
//        otherIds.append(getQueryCacheIds(AllConstants.ON_HAND))
//                .append(getQueryCacheIds(AllConstants.ON_HAND_LIST));
        if (TextUtils.isEmpty(query)) {
            List<String> list = DBApi.getInstance().queryDocketLogId(truckNo);
            syncDocket(list, truckNo, AllConstants.LOG_LIST, "");
        } else {
            syncDocket(AllConstants.LOG_LIST, query, "");
        }
    }

    private void syncDocketOnHandList() {
        syncPosition = 2;
        String truckNo = SPUtil.getInstance().getString(AllConstants.TRUCK_NAME);
        String query = DBApi.getInstance().getQueryCacheMap(AllConstants.ON_HAND_LIST);
        // 请求时要加上其他两个obj里面的ids
//        StringBuilder otherIds = new StringBuilder();
//        otherIds.append(getQueryCacheIds(AllConstants.ON_HAND))
//                .append(getQueryCacheIds(AllConstants.LOG_LIST));
        if (TextUtils.isEmpty(query)) {
            List<String> list = DBApi.getInstance().queryDocketListId(truckNo);
            syncDocket(list, truckNo, AllConstants.ON_HAND_LIST, "");
        } else {
            syncDocket(AllConstants.ON_HAND_LIST, query, "");
        }
    }

    private String getQueryCacheIds(String key) {
        String logQueryStr = DBApi.getInstance().getQueryCacheMap(key);
        if (!TextUtils.isEmpty(logQueryStr)) {
            SyncBean logQuery = (SyncBean) GsonUtil.getInstance().fromJson(logQueryStr, SyncBean.class);
            if (!TextUtils.isEmpty(logQuery.getSynObjIds())) {
                return "," + logQuery.getSynObjIds();
            }
        }
        return "";
    }

    private void syncDocket(String mapKey, String queryJson, String otherIds) {
        SyncBean query = (SyncBean) GsonUtil.getInstance().fromJson(queryJson, SyncBean.class);
        if (TextUtils.isEmpty(query.getOldTruckNo())) {
            query.setOldTruckNo(query.getTruckNo());
            queryJson = GsonUtil.getInstance().toJson(query);
            DBApi.getInstance().setQueryCacheMap(mapKey, queryJson);
        }
        if (!otherIds.isEmpty()) {
            String objIds = query.getSynObjIds();
            query.setSynObjIds(TextUtils.isEmpty(objIds) ? otherIds.substring(1) : objIds.contains(otherIds) ? objIds : (objIds + otherIds));
            queryJson = GsonUtil.getInstance().toJson(query);
        }
        mPresenter.syncModel(mapKey, queryJson,query.getTruckNo());
    }

    private void syncDocket(List<String> list, String truckNo, String mapKey, String otherIds) {
        String json = getSyncBean(getSyncDocket(), list, truckNo, otherIds);
        DBApi.getInstance().setQueryCacheMap(mapKey, json);
        mPresenter.syncModel(mapKey, json,truckNo);
    }

    private String getSyncBean(String url, List<String> list, String truckNo, String otherIds) {
        SyncBean bean = new SyncBean();
        if (list != null && !list.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (String id : list) {
                sb.append(",").append(id);
            }
            bean.setSynObjIds(sb.substring(1));
        }
//        if (!otherIds.isEmpty()) {
//            String objIds = bean.getSynObjIds();
//            bean.setSynObjIds(TextUtils.isEmpty(objIds) ? otherIds.substring(1) : objIds.contains(otherIds) ? objIds : (objIds + otherIds));
//        }
        bean.setSynObj(url);
        bean.setTruckNo(truckNo);
        bean.setOldTruckNo(truckNo);
        return GsonUtil.getInstance().toJson(bean);
    }

    @Override
    public void onSyncDocketSuccess(ApiResultData<List<Docket>> apiResultData, String mapKey,String postTruckNo) {
        if (apiResultData.getStatus() != 2000) {
            downloadError(apiResultData.getMessage());
            return;
        }
        List<Docket> data = apiResultData.getData();
        if (data == null || data.isEmpty()) {
            setQueryCache(mapKey, "");
        } else {
            String ids = DBApi.getInstance().insertDockets(data,postTruckNo);
            setQueryCache(mapKey, ids);
        }
        downloadSuccess();
    }

    @Override
    public void onSyncDocketFails(Exception e) {
        downloadFail();
    }

    private void setQueryCache(String mapKey, String ids) {
        try {
//            DBApi.getInstance().setAllQueryCacheMap(ids);
            DBApi.getInstance().setQueryCacheIds(mapKey, ids);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendDownloading() {
//        if (isDownload) {
        if (SyncStatus.isSync()) {
            return;
        }
        SyncStatus.setSync(true);
//        isDownload = true;
        onSyncListener.onSyncListener(HandleCode.MSG_DOWNLOADING, null);
    }

    private void downloadFail() {
        SPUtil.getInstance().putString(AllConstants.SYNC_TYPE, AllConstants.UPLOAD_DOCKET_INTERVAL);
//        LogUtil.getInstance().insertOrReplaceData("下載數據失敗：网络异常");
        SyncStatus.setSync(false);
//        isDownload = false;
        onSyncListener.onSyncListener(HandleCode.MSG_DOWNLOAD_FAIL, null);
    }

    private void downloadError(String msg) {
        SPUtil.getInstance().putString(AllConstants.SYNC_TYPE, AllConstants.UPLOAD_DOCKET_INTERVAL);
        LogUtil.getInstance().insertOrReplaceData("下載數據失敗：" + msg);
        SyncStatus.setSync(false);
//        isDownload = false;
        onSyncListener.onSyncListener(HandleCode.MSG_DOWNLOAD_ERROR, msg);
    }

    private void downloadSuccess() {
        SPUtil.getInstance().putString(AllConstants.SYNC_TYPE, AllConstants.UPLOAD_DOCKET_INTERVAL);
        SyncStatus.setSync(false);
//        isDownload = false;
        onSyncListener.onSyncListener(HandleCode.MSG_DOWNLOAD_SUCCESS, null);
    }

    private IOnSyncListener onSyncListener;

    public void setOnSyncListener(IOnSyncListener onSyncListener) {
        this.onSyncListener = onSyncListener;
    }
}
